import { InjectModel } from '@nestjs/mongoose';
import {
  ConnectedSocket,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Model } from 'mongoose';
import { Socket } from 'socket.io';
import {
  Message,
  MessageDocument,
  MessageWithOutId,
} from '../message/scheme/message.scheme';

@WebSocketGateway({
  cors: {
    origin: '*',
  },
})
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  constructor(
    @InjectModel(Message.name) private readonly message: Model<MessageDocument>,
  ) {}

  private onlineNumber = 0;

  private sendAll(socket: Socket, ...args: Parameters<Socket['emit']>) {
    socket.emit(...args);
    socket.broadcast.emit(...args);
  }

  handleConnection(socket: Socket) {
    this.onlineNumber++;
    this.sendAll(socket, 'someOneConnect', this.onlineNumber);
  }

  handleDisconnect(socket: Socket) {
    this.onlineNumber--;
    this.sendAll(socket, 'someOneDisConnect', this.onlineNumber);
  }

  @SubscribeMessage('delete')
  delete(@MessageBody() id: string, @ConnectedSocket() socket: Socket) {
    this.message.deleteOne({ _id: id }).then(() => {
      this.sendAll(socket, 'delete', id);
    });
    return;
  }

  @SubscribeMessage('add')
  add(
    @MessageBody() message: MessageWithOutId,
    @ConnectedSocket() socket: Socket,
  ) {
    this.message.create(message).then((message) => {
      this.sendAll(socket, 'add', message);
    });
    return;
  }
}
